import {loginAPI, getUserInfoApi,getBestUserInfoApi} from '@/api/user'
import {setToken, getToken,removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}

const getters = {}

const mutations = {
  setToken(state,newToken) {
    setToken(newToken)
    state.token = newToken
  },
  setUserInfo(state,newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 删除token,用户信息
  logout(state){
    state.token = ''
    removeToken()
    state.userInfo = {}
  }
}


const actions = {
  // 调登录接口
  login(store,loginForm) {
    return new Promise((resolve, reject) => {
      loginAPI(loginForm).then(res => {
        const token = res.data
        store.commit('setToken',token)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  async getUserInfo(store){
    const res =  await getUserInfoApi()
    const res2 = await getBestUserInfoApi(res.data.userId)
    // res2.data.staffPhoto = 'https://www.baidu.com/qqq'
    const baseData = {...res.data, ...res2.data}
    store.commit('setUserInfo',baseData)
    // 之后使用
    return baseData
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
